import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class L102_2 {
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            ArrayList<List<Integer>> result = new ArrayList<>();
            if (root == null) {
                return result;
            }

            LinkedList<TreeNode> list = new LinkedList<>();
            list.offer(root);
            while (!list.isEmpty()) {
                int size = list.size();
                ArrayList<Integer> list1 = new ArrayList<>();
                while (size > 0) {
                    TreeNode node = list.poll();
                    list1.add(node.val);
                    if (node.left != null) {
                        list.offer(node.left);
                    }
                    if (node.right != null) {
                        list.offer(node.right);
                    }
                    size--;
                }
                result.add(list1);
            }
            return result;
        }
    }
}
